<template>
  <div class="data-table">
    <div class="table" ref="chartDom" style="width: 100%; height: 100%;"></div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';

// 获取 props 并定义 options 作为 prop
const props = defineProps({
  options: Object
});

// 创建一个响应式引用来保存DOM元素
const chartDom = ref(null);
let chartInstance = null;

// 初始化ECharts实例并设置配置项
const initChart = () => {
  if (chartDom.value) {
    chartInstance = echarts.init(chartDom.value);
    if (props.options) {
      chartInstance.setOption(props.options);
    }
  }
};

onMounted(async () => {
  await nextTick(); // 确保DOM已经渲染完成
  initChart();

  // 监听窗口大小变化，自动调整图表大小
  window.addEventListener('resize', resizeChart);
});

// 销毁ECharts实例
onUnmounted(() => {
  if (chartInstance != null && chartInstance.dispose) {
    chartInstance.dispose();
  }
  window.removeEventListener('resize', resizeChart);
});

// 监听 props.options 变化并更新图表
watch(() => props.options, (newOptions) => {
  if (chartInstance && newOptions) {
    chartInstance.setOption(newOptions);
  }
}, { deep: true });

// 调整图表大小
const resizeChart = () => {
  if (chartInstance) {
    chartInstance.resize();
  }
};
</script>

<style scoped>
/* 添加一些CSS样式来美化图表容器（可选） */
.data-table {
  width: 100%;
  height: 100%;
  min-width: 350px;
  min-height: 400px;
}

</style>
